/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <QToolTip>
#include <QImage>
#include <QApplication>
#include <QPainter>
#include <QTextDocument>
#include "postitemdelegate.h"
#include "postitemmodel.h"
#include "postdocument.h"
#include "postwidget.h"
#include "log.h"
#include "components/thread.h"
#include "components/post.h"

PostItemDelegate::PostItemDelegate(PostItemView* view, QObject* parent) : m_view(view)
{
	m_postIDFont = new QFont("Helvetica", 10, 63); //FIXME hardcoded value
}

PostItemDelegate::~PostItemDelegate()
{
	delete m_postIDFont;
}

/// FIXME a lot of hardcoded values
void PostItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	//log(llDebug, "paint: %d/%d", index.row(), index.column());
	if(index.column() == 0)
	{
		QWidget* w = m_view->getWidget(index);
		if(!w)
			return;
		(static_cast<PostWidget*>(w))->doPaint(painter, option.rect);

		if(m_view->currentIndex() == index)
		{
			QRect r = option.rect;
			r.adjust(0, 0, -1, -1);
			r.setWidth(w->size().width());
			painter->save();
			QPen pen((static_cast<PostWidget*>(w))->postStyle()->linkColor());
			painter->setPen(pen);
			painter->drawRoundedRect(r, (static_cast<PostWidget*>(w))->postStyle()->borderRadius(), (static_cast<PostWidget*>(w))->postStyle()->borderRadius());
			painter->restore();
		}
	}
}

QSize PostItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	//log(llDebug, "sizeHint: %d/%d", index.row(), index.column());
	if(index.column() == 0)
	{
		PostWidget* w = m_view->getWidget(index);
		if(w)
			return w->size();
	}
	return QSize();
}

bool PostItemDelegate::helpEvent(QHelpEvent* event, QAbstractItemView* view, const QStyleOptionViewItem& option, const QModelIndex& index)
{
	QWidget* w = m_view->getWidget(index);
	if(!w)
	{
		QToolTip::hideText();
		return false;
	}
	QPoint p(event->pos().x() - option.rect.left(), event->pos().y() - option.rect.top());
	(static_cast<PostWidget*>(w))->help(p, event->globalPos());
	return true;
}

